from django.http import HttpResponseRedirect
from django.utils.deprecation import MiddlewareMixin

from seclab import settings
import re
# 未登录可访问的页面或正则
EXEMPT_URLS = [settings.LOGIN_URL.lstrip('/'), ]

if hasattr(settings, 'LOGIN_EXEMPT_URLS'):
    EXEMPT_URLS.extend([expr.lstrip('/') for expr in settings.LOGIN_EXEMPT_URLS])


class userVaild(MiddlewareMixin):
    def process_request(self, request):
        if 'user' not in request.session or not request.session['user']:
            path = request.path_info.lstrip('/')
            if not any(re.search(m, path) for m in EXEMPT_URLS):
                return HttpResponseRedirect(settings.LOGIN_URL)

    def process_view(self, request, view_func, view_func_args, view_func_kwargs):
        print('process_view')

    def process_response(self, request, response):
        print('process_response')
        return response